package com.jp.knowledge.my.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.SelectDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.activity.AuditJoinActivity;
import com.jp.knowledge.my.adapter.AuditListAdapter;
import com.jp.knowledge.my.model.ColleagueAuditModel;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.RecycleViewDiver;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("ValidFragment")
@ContentView(R.layout.fragment_audit_list)
public class AuditListFragment extends BaseFragment implements AuditListAdapter.AuditClickListener,
        ResultSubscriber.OnResultListener, View.OnClickListener, AuditJoinActivity.AuditSubject, AuditJoinActivity.AuditObserver, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, SelectDialog.OnSelectDialogItemClickListener {

    private static final int GET_AUDIT_LIST = 0x01;
    private static final int COMMIT_AUDIT = 0x02;

    private View contentView;

    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;
    @ViewInject(R.id.can_content_view)
    private RecyclerView mAuditRv;
    @ViewInject(R.id.audit_join_bg)
    private LinearLayout mAuditBg;
    @ViewInject(R.id.audit_join_Tv)
    private TextView mAuditTv;

    private int type;
    private int page;
    private List<ColleagueAuditModel> auditModels;
    private AuditListAdapter mSelectAdapter;
    private CommDialog refuseAuditDialog;
    private SelectDialog auditSeletcDialog;
    private int auditPosition;

    private List<AuditJoinActivity.AuditObserver> observerList;
    private OrganizaModel  company;
    private String paramId;
    public AuditListFragment  newInstance(OrganizaModel  company){
            this.company=company;
        if(company!=null){
            int type = company.getCompanyType();
            if(type==2)paramId = company.getClassId();
            else paramId = company.getCompanyId();
        }
        this.type = 0;
        this.page = 1;
        this.auditPosition = 0;
        this.auditModels = new ArrayList<>();
        this.observerList = new ArrayList<>();
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        this.contentView = x.view().inject(this, inflater, container);
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if(contentView != null)
            return;
        initReeceRv();

        mAuditTv.setText("还没有待审核的申请");

        refreshLayout.setRefreshEnabled(true);
        refreshLayout.setLoadMoreEnabled(true);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        refuseAuditDialog = new CommDialog(mContext);
        refuseAuditDialog.setEditHint("请输入拒绝理由");
        refuseAuditDialog.setLeft("取消");
        refuseAuditDialog.setRight("拒绝");
        refuseAuditDialog.setRightClickDismiss(false);
        refuseAuditDialog.setRightListener(this);

        auditSeletcDialog = new SelectDialog(mContext);
        auditSeletcDialog.setTitle("选择操作");
        auditSeletcDialog.setCancelBtn("取消");
        auditSeletcDialog.addItem("同意");
        auditSeletcDialog.addItem("拒绝");
        auditSeletcDialog.setOnDialogItemClickListener(this);

        refreshLayout.autoRefresh();
    }

    private void setViewVisibility(){
        if(auditModels != null && auditModels.size() > 0){
//            refreshLayout.setVisibility(View.VISIBLE);
            mAuditBg.setVisibility(View.GONE);
        } else{
//            refreshLayout.setVisibility(View.GONE);
            mAuditBg.setVisibility(View.VISIBLE);
        }
    }

    private void initReeceRv() {
        mAuditRv.setHasFixedSize(true);
        mAuditRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAuditRv.addItemDecoration(new RecycleViewDiver(getActivity(), LinearLayout.HORIZONTAL));
        mSelectAdapter = new AuditListAdapter(getActivity(), new ArrayList<ColleagueAuditModel>());
        mSelectAdapter.setAuditClickListener(this);

        mAuditRv.setAdapter(mSelectAdapter);
    }

    @Override
    public void onRefresh() {
        page = 1;
        getAuditList(page);
    }

    @Override
    public void onLoadMore() {
        getAuditList(++page);
    }

    private void getAuditList(int page){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("type", company.getCompanyType());
        param.addProperty("id",paramId);
        param.addProperty("page", page);
        HttpHelper.getInstance(mContext).getAuditList(param, GET_AUDIT_LIST, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == GET_AUDIT_LIST){
            refreshLayout.refreshComplete();
            refreshLayout.loadMoreComplete();
        } else{
            loadingDialog.cancel();
        }
    }
    @Override
    public void onError(int requestType) {
        if(requestType == GET_AUDIT_LIST) {
            loadingDialog.cancel();
            if(this.isVisible())
                ToasUtil.toast(mContext, "抱歉，数据获取失败，请稍后重试");
        } else if(requestType == COMMIT_AUDIT){
            auditModels.get(auditPosition).setStatus(type);
            ToasUtil.toast(mContext, "抱歉，操作失败，请稍后重试");
        }
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
            return;
        }
        if(requestType == GET_AUDIT_LIST){
            if(page == 1)
                auditModels.clear();
            List<ColleagueAuditModel> tempModes = data.getList(ColleagueAuditModel.class);
            if(tempModes != null && tempModes.size() > 0) {
                for(ColleagueAuditModel auditModel : tempModes)
                    auditModel.setStatus(type);
                auditModels.addAll(tempModes);
            }
            mSelectAdapter.updateAdapter(auditModels);
            setViewVisibility();
        } else if(requestType == COMMIT_AUDIT){
            ColleagueAuditModel auditModel = auditModels.get(auditPosition);
            // 向所有观察者发出审核完成通知
            for(AuditJoinActivity.AuditObserver observer : observerList)
                observer.update(auditModel);
            ToasUtil.toast(mContext, "操作成功");
        }
    }

    @Override
    public void onSelectItemClick(int position) {
        if(position == 0) {
            auditModels.get(auditPosition).setStatus(1);
            commitAudit(1, null,auditModels.get(position).getAuditState());
            loadingDialog.show();
        } else{
            refuseAuditDialog.setEditText("");
            refuseAuditDialog.show();
        }
    }

    private void commitAudit(int type, String reason,int action){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id", auditModels.get(auditPosition).getUserId());
        param.addProperty("organizeId",paramId);
        param.addProperty("recommendAction",action);
        param.addProperty("type", company.getCompanyType());
        if(type == 2)
            param.addProperty("reason", reason);
        HttpHelper.getInstance(mContext).commitAudit(param, COMMIT_AUDIT, this);
        loadingDialog.show();
    }

    @Override
    public void onClick(int position) {
        auditPosition = position;
        int status = auditModels.get(position).getAuditState();
        if(status==0){//待审核的状态
            auditSeletcDialog.show();
        }
//        if(type == 0){
//            auditSeletcDialog.show();
//        } else if(type == 1){
//            refuseAuditDialog.setEditText("");
//            refuseAuditDialog.show();
//        } else if(type == 2){
//            auditModels.get(auditPosition).setStatus(1);
//            commitAudit(1, null);
//            loadingDialog.show();
//        }
    }

    @Override
    public void onClick(View v) {
        if(refuseAuditDialog.getEditText().trim().length() == 0){
            ToasUtil.toast(mContext, "请输入有效的拒绝理由");
            return;
        }
        auditModels.get(auditPosition).setStatus(2);
        commitAudit(2, refuseAuditDialog.getEditText(),auditModels.get(auditPosition).getAuditState());
        refuseAuditDialog.dismiss();
        loadingDialog.show();
    }

    @Override
    public void update(ColleagueAuditModel model) {
        if(!auditModels.remove(model) && model.getStatus() == type)
            auditModels.add(0, model);
        mSelectAdapter.updateAdapter(auditModels);
        setViewVisibility();
    }

    @Override
    public void addObserver(AuditJoinActivity.AuditObserver observer) {
        observerList.add(observer);
    }
}
